Partial Public Class FrmNCND

    Inherits System.Web.UI.Page
    Public Factura As CapaDeNegocios.nFactura = New CapaDeNegocios.nFactura
    Public Cliente As CapaDeNegocios.nCliente = New CapaDeNegocios.nCliente
    Public NotaDeCredito As CapaDeNegocios.nNotaDeCredito = New CapaDeNegocios.nNotaDeCredito
    Public NotaDeDebito As CapaDeNegocios.nNotaDeDebito = New CapaDeNegocios.nNotaDeDebito
    Public CategoriaFiscal As CapaDeNegocios.nCategoriaFiscal = New CapaDeNegocios.nCategoriaFiscal
    Public Talonario As CapaDeNegocios.nTalonario = New CapaDeNegocios.nTalonario
    Public TipoTalonario As CapaDeNegocios.nTipoTalonario = New CapaDeNegocios.nTipoTalonario
    Dim IdFactura As String
    Dim IdTalonario As String
    Dim IdTipo As String
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Session("Login") = "Anonimo" Then
            Response.Redirect("/")
        End If

        If Not Page.IsPostBack Then
            HFIdTipo.Value = Request.QueryString("IdTipo")
            HfIdFactura.Value = Request.QueryString("IdFactura")
            HfIdTrabado.Value = Request.QueryString("Trabado")

            IdTipo = Request.QueryString("IdTipo")
            If IdTipo = "NC" Then
                LblTitulo.Text = "Administracion de Notas de Credito"
            Else
                LblTitulo.Text = "Administracion de Notas de Debito"
            End If
            IdFactura = Request.QueryString("IdFactura")
            If HfIdTrabado.Value = "Si" Then
                LnkGuardar.Visible = False
            End If

            Iniciar()
        End If
    End Sub
    Sub Iniciar()
        If HFIdTipo.Value.ToString() <> "" And HfIdFactura.Value.ToString() <> "" Then
            IdFactura = HfIdFactura.Value.ToString()
            IdTipo = HFIdTipo.Value.ToString()
            Dim dts As DataSet = Factura.BuscarFiltrado(IdFactura, "", "", "", "", "", "", "", "", "")
            LblError.Text = ""
            TxtImporte.Text = "0,00"
            LblFecha.Text = Now.Date.ToShortDateString()
            LblFactura.Text = dts.Tables(0).Rows(0)("Numero").ToString()
            CboConcepto.Items.Clear()
            CboConcepto.Items.Add(New ListItem("Error de Facturacion", "Error de Facturacion"))
            CboConcepto.SelectedIndex = 0

            If IdTipo = "ND" Then
                CboConcepto.Items.Add(New ListItem("Pago Fuera de Termino", "Pago Fuera de Termino"))
                If dts.Tables(0).Rows(0)("CodigoCategoria").ToString() = "1" Then
                    LblNumero.Text = "A-0001-"
                    TxtNumero.Text = Replace(NotaDeDebito.ObtenerNumero("1").ToString().PadLeft(8), " ", "0")
                Else
                    LblNumero.Text = "B-0001-"
                    TxtNumero.Text = Replace(NotaDeDebito.ObtenerNumero("2").ToString().PadLeft(8), " ", "0")
                End If
            Else
                Dim dtsNC As DataSet = NotaDeCredito.BuscarFiltrado("", "", "", "", IdFactura, "", "")
                Dim MaximoPermitido As Double = 0
                For Each row As DataRow In dtsNC.Tables(0).Rows
                    If row("Estado").ToString() <> "ANULADA" Then
                        MaximoPermitido = MaximoPermitido + CDbl(row("Total").ToString())
                    End If

                Next
                If dts.Tables(0).Rows(0)("CodigoCategoria").ToString() = "1" Then
                    LblNumero.Text = "A-0001-"
                    TxtNumero.Text = Replace(NotaDeCredito.ObtenerNumero("1").ToString().PadLeft(8), " ", "0")
                Else
                    LblNumero.Text = "B-0001-"
                    TxtNumero.Text = Replace(NotaDeCredito.ObtenerNumero("2").ToString().PadLeft(8), " ", "0")
                End If
                If RvTotal.MinimumValue > (CDbl(dts.Tables(0).Rows(0)("Total").ToString()) - MaximoPermitido).ToString() Then
                    LnkGuardar.Visible = False
                Else
                    LnkGuardar.Visible = True And HfIdTrabado.Value <> "Si"
                    RvTotal.MaximumValue = (CDbl(dts.Tables(0).Rows(0)("Total").ToString()) - MaximoPermitido).ToString()
                End If
                RvTotal.Text = "Maximo : " + (CDbl(dts.Tables(0).Rows(0)("Total").ToString()) - MaximoPermitido).ToString()
            End If
            TxtNumero.Enabled = CDbl(TxtNumero.Text) = 1
            VerificarTalonario()
            LlenarCuerpo()
        End If

    End Sub
    Sub VerificarTalonario()
        Dim dtsTipoTalonario As DataSet
        Dim VarError As Boolean = False
        If IdTipo = "NC" Then
            If TipoTalonario.Buscar("", LblNumero.Text.Substring(0, 1), "NOTA DE CREDITO").Tables(0).Rows.Count() > 0 Then
                dtsTipoTalonario = Talonario.BuscarFiltrado("", TxtNumero.Text, TxtNumero.Text, "", "", "3", TipoTalonario.Buscar("", LblNumero.Text.Substring(0, 1), "NOTA DE CREDITO").Tables(0).Rows(0)("IdTipoTalonario").ToString())
            Else
                VarError = True

            End If
        Else
            If TipoTalonario.Buscar("", LblNumero.Text.Substring(0, 1), "NOTA DE DEBITO").Tables(0).Rows.Count() > 0 Then
                dtsTipoTalonario = Talonario.BuscarFiltrado("", TxtNumero.Text, TxtNumero.Text, "", "", "3", TipoTalonario.Buscar("", LblNumero.Text.Substring(0, 1), "NOTA DE DEBITO").Tables(0).Rows(0)("IdTipoTalonario").ToString())
            Else
                VarError = True
            End If
        End If
        If VarError Then
            LblError.Text = "Error, Talonario no Existe."
            LnkGuardar.Visible = False
        Else
            If dtsTipoTalonario.Tables(0).Rows.Count() = 0 Then
                LblError.Text = "Error, Talonario no Habilitado."
                LnkGuardar.Visible = False
            Else
                IdTalonario = dtsTipoTalonario.Tables(0).Rows(0)("IdTalonario").ToString()
                HfIdTalonario.Value = IdTalonario
                LblError.Text = ""
            End If
        End If
        'If TxtNumero.Text <> "00000001" Then
        'TxtNumero.Enabled = False
        'Else
        'TxtNumero.Enabled = True
        'End If
        'RVNumeracion.MinimumValue = TxtNumero.Text
    End Sub

    Sub LlenarCuerpo()
        If HFIdTipo.Value.ToString() = "NC" Then
            GridComprobantes.DataSource = NotaDeCredito.BuscarFiltrado("", "", "", "", HfIdFactura.Value.ToString(), "", "")
        Else
            GridComprobantes.DataSource = NotaDeDebito.BuscarFiltrado("", "", "", "", HfIdFactura.Value.ToString(), "", "")
        End If
        GridComprobantes.DataBind()
    End Sub

    Protected Sub LnkGuardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LnkGuardar.Click
        If CDbl(TxtImporte.Text) > 0 Then
            If HFIdTipo.Value.ToString() = "NC" Then
                If Not NotaDeCredito.Insertar((LblNumero.Text + TxtNumero.Text.PadLeft(8).Replace(" ", "0")).Replace("-", ""), HfIdTalonario.Value.ToString(), HfIdFactura.Value.ToString(), TxtImporte.Text, CboConcepto.SelectedValue.ToString()) Then
                    LblError.Text = "Error, no se pudo insertar la Nota de Credito"
                Else

                    Session("DtsImpresionDeFactura") = NotaDeCredito.PrepararImpresion(HfIdFactura.Value.ToString, CboConcepto.Text, TxtImporte.Text, (LblNumero.Text + TxtNumero.Text.PadLeft(8).Replace(" ", "0")).Replace("-", ""))
                    Response.Write("<SCRIPT LANGUAGE='JavaScript'> var popup = window.open('../Reportes/RptImpresionComprobante.aspx',(new Date().getTime()),'Width=800,Height=600,Scrollbars=YES,Resizable=YES,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO') </SCRIPT>")

                    Iniciar()
                End If
            Else
                If Not NotaDeDebito.Insertar((LblNumero.Text + TxtNumero.Text.PadLeft(8).Replace(" ", "0")).Replace("-", ""), HfIdTalonario.Value.ToString(), HfIdFactura.Value.ToString(), TxtImporte.Text, CboConcepto.SelectedValue.ToString()) Then
                    LblError.Text = "Error, no se pudo insertar la Nota de Debito"
                Else
                    Session("DtsImpresionDeFactura") = NotaDeDebito.PrepararImpresion(HfIdFactura.Value.ToString, CboConcepto.Text, TxtImporte.Text, (LblNumero.Text + TxtNumero.Text.PadLeft(8).Replace(" ", "0")).Replace("-", ""))
                    Response.Write("<SCRIPT LANGUAGE='JavaScript'> var popup = window.open('../Reportes/RptImpresionComprobante.aspx',(new Date().getTime()),'Width=800,Height=600,Scrollbars=YES,Resizable=YES,Location=NO,Menubar=NO,Status=NO,Titlebar=NO,Toolbar=NO') </SCRIPT>")
                    Iniciar()
                End If
            End If

            'TxtImporte.Text = "0,00"
            'TxtNumero.Text = (CInt(TxtNumero.Text) + 1).ToString().PadLeft(8).Replace(" ", "0")
            'VerificarTalonario()
        End If
        'LlenarCuerpo()
    End Sub

    Protected Sub GridComprobantes_RowCommand(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridComprobantes.RowCommand
        If e.CommandName = "Anular" Then
            If HFIdTipo.Value.ToString() = "NC" Then
                NotaDeCredito.Eliminar(e.CommandSource.Parent.Parent.FindControl("HFIdComprobante").Value.ToString())
            Else
                NotaDeDebito.Eliminar(e.CommandSource.Parent.Parent.FindControl("HFIdComprobante").Value.ToString())
            End If
            Iniciar()
            'LlenarCuerpo()
        End If
    End Sub

    Protected Sub GridComprobantes_RowDataBound(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridComprobantes.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim IntLnkAnular As LinkButton = e.Row.FindControl("LnkAnular")
            Dim IntLblEstado As Label = e.Row.FindControl("LblEstado")
            IntLnkAnular.Visible = IntLblEstado.Text <> "ANULADA"
            If HfIdTrabado.Value = "Si" Then
                IntLnkAnular.Visible = False
            End If

        End If

    End Sub
End Class